package com.hd.util.qrcode;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;  
  
 /**
  * 去空白边框后生成二维码
  * @author hzhh123
  * @Date 2019年3月4日 下午3:27:23
  */
 @SuppressWarnings("unchecked")
public class TwoDimensionCode {  
      
    /** 
     * 生成二维码(QRCode)图片 
     * @param content 存储内容 
     * @param imgPath 图片路径 
     * @throws Exception  
     */  
      
    public static void encoderQRCode(String content, String imgPath) throws Exception {  
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();  
        Map hints = new HashMap();  
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
        hints.put(EncodeHintType.MARGIN, 0);  
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  
        int width = 280;  
        int height = 280;  
        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);  
        bitMatrix = updateBit(bitMatrix, 2);  
        MatrixToImageWriter.writeToFile(bitMatrix, "PNG", new File(imgPath));  
    }  
      
    /** 
     * 去掉空白的边框 
     * @param matrix 
     * @param margin 
     * @return 
     */  
    private static BitMatrix updateBit(BitMatrix matrix, int margin) {  
        int tempM = margin * 2;  
        int[] rec = matrix.getEnclosingRectangle(); // 获取二维码图案的属性  
        int resWidth = rec[2] + tempM;  
        int resHeight = rec[3] + tempM;  
        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); // 按照自定义边框生成新的BitMatrix  
        resMatrix.clear();  
        for (int i = margin; i < resWidth; i++) { // 循环，将二维码图案绘制到新的bitMatrix中  
            for (int j = margin; j < resHeight; j++) {  
                if (matrix.get(i - margin + rec[0], j - margin + rec[1])) {  
                    resMatrix.set(i, j);  
                }  
            }  
        }  
        return resMatrix;  
    }  
    public static void main(String[] args) throws Exception {  
		// 二维码字符串  
		String qrCodeData = "https://www.baidu.com/";  
		// 二维码名称  
		String filePath = "D:\\QRCode.png";  
		encoderQRCode(qrCodeData, filePath);
    }
}  